One of the most useful purposes of LiveControls is to create an application which constantly updates the browser with updated information. Good examples of this would be real-time sports scores, real-time stocks, current weather, current news, or any other constantly updated data. The technique for creating an application like these is to use LiveTimer and periodically poll the data for new changes.
To use LiveTimer to create a "data-streaming" application, use the following steps: (these steps demonstrate the simple operation of showing the current system time.
- Follow the steps outlined in Using LiveControls to add a LiveLabel and a LiveTimer to the WebForm.
- To add code using Code Behind double click the WebForm to bring up the Page_Load event. Add the following code to configure and start the LiveTimer.
The following code demonstrates configuring and starting the LiveTimer.
[C#] // Set the LiveTimer to fire every 500 milliseconds. LiveTimer1.Interval = 500; // Start the LiveTimer LiveTimer1.Start(); [Visual Basic] ' Set the LiveTimer to fire every 500 milliseconds. LiveTimer1.Interval = 500 ' Start the LiveTimer LiveTimer1.Start()
- Now implement the LiveTimer.Tick event. First, "wire-up" the event as appropriate for your environment. Within this event, add the following code to update the LiveLabel with the current time.
The following code demonstrates implementing the LiveTimer.Tick event.
[C#] private void LiveTimer1_Tick(object sender, System.EventArgs e) { LiveLabel1.Text = System.DateTime.Now.ToLongTimeString(); } [Visual Basic] Private Sub LiveTimer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles LiveTimer1.Tick LiveLabel1.Text = System.DateTime.Now.ToLongTimeString() End Sub
- Compile and run the Web application. You should see the time constantly and smoothly updating.